/**
 * Copyright 2011, Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.codelab;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;

/**
 * This servlet responds to the request corresponding to transacaos. The class
 * creates and manages the TransacaoEntity
 * 
 * @author
 */
@SuppressWarnings("serial")
public class TransacaoServlet extends BaseServlet {

	private static final Logger logger = Logger
			.getLogger(TransacaoServlet.class.getCanonicalName());

	/**
	 * Searches for the entity based on the search criteria and returns result
	 * in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining Transacao listing");
		String searchBy = req.getParameter("transacao-searchby");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		if (searchFor == null || searchFor.equals("")) {
			Iterable<Entity> entities = Transacao.getAllTransacoes();
			out.println(Util.writeJSON(entities));
		} else if (searchBy == null || searchBy.equals("trans_id")) {
			Iterable<Entity> entities = Transacao.getTransacao(searchFor);
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("midia_number")) {
			Iterable<Entity> entities = Transacao.getTransacaoForMidiaNumber(searchFor);
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("cliente_name")) {
			Iterable<Entity> entities = Transacao.getTransacaoForCliente(searchFor);
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("localidade_id")) {
			Iterable<Entity> entities = Transacao.getTransacaoForLocalidade(searchFor);
			out.println(Util.writeJSON(entities));
		}else {
			logger.log(Level.INFO, "Invalid search by: transacao-searchby=" + searchBy);
		}
	}

	/**
	 * Creates entity and persists the same
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating Transacao");
		String trans_id = req.getParameter("trans_id");
		String trans_type = req.getParameter("trans_type");
		String trans_price = req.getParameter("trans_price");
		String trans_data = req.getParameter("trans_data");
		String trans_hora = req.getParameter("trans_hora");
		String estabelecimento_nome = req.getParameter("estabelecimento_nome");
		String cliente_name = req.getParameter("cliente_name");
		String midia_name = req.getParameter("midia_name");
		String localidade_id = req.getParameter("localidade_id");

		Transacao.createOrUpdateTransacao(trans_id, trans_type, new BigDecimal(trans_price).doubleValue(),
				trans_data, trans_hora, estabelecimento_nome, cliente_name,
				midia_name, localidade_id);
	}

	/**
	 * Delete the entity from the datastore. Throws an exception if there are
	 * any orders associated with the transacao and ignores the delete action
	 * for it.
	 */
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Deleting Transacao");
		String transacaoKey = req.getParameter("id");
		PrintWriter out = resp.getWriter();
		Iterable<Entity> entities = Util.listEntities("Transacao", "trans_id",
				transacaoKey);
		try {
			Entity e = Transacao.getSingleTransacao(transacaoKey);
			Util.deleteFromCache(e.getKey());
			Util.deleteEntity(e.getKey());
			out.print("Transacao deleted successfully.");
		} catch (Exception e) {
			String msg = Util.getErrorResponse(e);
			out.print(msg);
		}
	}

	/**
	 * Redirects to delete or insert entity based on the action in the HTTP
	 * request.
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}
}